package com.movie.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {

    private static String DB_URL;
    private static String DB_USERNAME;
    private static String DB_PASSWORD;

    static {
        Properties properties = new Properties();
        try(InputStream input = DBUtil.class.getClassLoader().getResourceAsStream("db.properties")){
            if(input == null){
                System.err.println("Unable to find db.properties");
                throw new RuntimeException("Unable to find db.properties");
            }
            properties.load(input);
            DB_URL = properties.getProperty("db.url");
            DB_USERNAME = properties.getProperty("db.username");
            DB_PASSWORD = properties.getProperty("db.password");
        }catch (IOException e){
            System.err.println("Fail to load db.properties");
            throw new RuntimeException("Fail to load db.properties",e);
        }
    }

    public static Connection getConnection() throws SQLException {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        }catch (ClassNotFoundException e){
            System.err.println("Unable to find JDBC driver "+e.getMessage());
        }
        return DriverManager.getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
    }

    public  void testDatabaseConnection(){
        try(Connection connection = getConnection()){
            if (connection != null && connection.isValid(5)) {
                System.out.println("Database connection is successful!");
            }else {
                System.err.println("Database connection is failed!");
            }
        } catch (SQLException e) {
            System.err.println("Failed to establish database connection: "+e.getMessage());
        }
    }
}